package com.xiangyi.teachingsystem.admin.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.xiangyi.teachingsystem.entity.po.User;
import com.xiangyi.teachingsystem.entity.vo.Result;
import com.xiangyi.teachingsystem.service.UserService;
import com.xiangyi.teachingsystem.validation.groups.AdminOperUser;
import com.xiangyi.teachingsystem.validation.groups.Login;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;


@RestController
@RequestMapping("/adminUserOper")
public class AdminAdminUserController {
    @Autowired
    UserService userService;

    @PostMapping("/addOrUpdateAdmin")
    public Result addOrUpdateAdmin(@Validated(AdminOperUser.class) @RequestBody User user) {
        String phoneNum = user.getPhoneNum();
        if (user.getId() != null) {
            userService.update(user, new UpdateWrapper<User>()
                    .eq("id", user.getId())
                    .eq("admin_sign", true));
            return Result.success("管理员信息更新成功");
        }
        User userInfo = userService.getOne(new QueryWrapper<User>()
                .eq("phone_num", phoneNum)
                .eq("admin_sign", true));
        if (userInfo==null){
            user.setAdminSign(true);
            userService.save(user);
            return Result.success("管理员添加成功");
        }else {
            return Result.failure("手机号已存在");
        }

    }

    @GetMapping("/delAdmin")
    public Result delAdmin(@RequestParam Integer adminId) {
        try {
            User byId = userService.getById(adminId);
            if (byId != null) {
                userService.remove(new QueryWrapper<User>()
                        .eq("id", adminId)
                        .eq("admin_sign", true));
                return Result.success("管理员移除成功").setData(byId);
            }
            return Result.failure("管理员不存在");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.failure("服务器错误").setData(e.getMessage());
        }

    }

    @GetMapping("/adminList")
    public Result adminList() {
        List<User> adminList = userService.getBaseMapper().selectList(new QueryWrapper<User>()
                .eq("admin_sign", true));
        return Result.success("管理员列表查询成功").setData(adminList);
    }
}
